#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/hci.h>
#include <bluetooth/hci_lib.h>
#include <bluetooth/rfcomm.h>
#include <sys/socket.h>
#include <errno.h>

#define AVRCP_COMMAND_PLAY 0x44
#define AVRCP_COMMAND_PAUSE 0x45
#define AVRCP_COMMAND_STOP 0x46

void send_avrcp_command(const char *bdaddr_str, uint8_t command) {
    struct sockaddr_rc addr = { 0 };
    int s, status;
    char dest[18] = { 0 };

    // 解析蓝牙地址
    str2ba(bdaddr_str, &addr.rc_bdaddr);
    addr.rc_family = AF_BLUETOOTH;
    addr.rc_channel = 1; // RFCOMM channel

    // 创建 RFCOMM socket
    s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
    if (s < 0) {
        perror("Failed to create socket");
        return;
    }

    // 连接到蓝牙设备
    status = connect(s, (struct sockaddr *)&addr, sizeof(addr));
    if (status < 0) {
        perror("Failed to connect");
        close(s);
        return;
    }

    // 发送 AVRCP 命令
    uint8_t command_buffer[2];
    command_buffer[0] = command; // AVRCP command
    command_buffer[1] = 0; // Placeholder for additional data

    status = write(s, command_buffer, sizeof(command_buffer));
    if (status < 0) {
        perror("Failed to send command");
    } else {
        printf("AVRCP command sent: 0x%02X\n", command);
    }

    // 关闭 socket
    close(s);
}

int main(int argc, char *argv[]) {
    if (argc < 3) {
        fprintf(stderr, "Usage: %s <bdaddr> <command>\n", argv[0]);
        fprintf(stderr, "Commands: play, pause, stop\n");
        return 1;
    }

    const char *bdaddr_str = argv[1];
    const char *command_str = argv[2];
    uint8_t command;

    // 根据命令选择 AVRCP 命令
    if (strcmp(command_str, "play") == 0) {
        command = AVRCP_COMMAND_PLAY;
    } else if (strcmp(command_str, "pause") == 0) {
        command = AVRCP_COMMAND_PAUSE;
    } else if (strcmp(command_str, "stop") == 0) {
        command = AVRCP_COMMAND_STOP;
    } else {
        fprintf(stderr, "Invalid command: %s\n", command_str);
        return 1;
    }

    // 发送 AVRCP 命令
    send_avrcp_command(bdaddr_str, command);

    return 0;
} 


/*

听歌模式下需要的代码

sudo apt-get install bluez
sudo apt-get install libbluetooth-dev

   gcc bluetooth_avrcp_control.c -o avrcp_control -lbluetooth

   ./avrcp_control 00:1A:7D:DA:71:13 play

*/